//
//  StartPSWViewController.m
//  LFCWarmSystem
//
//  Created by 李福才 on 16/4/27.
//  Copyright © 2016年 李福才. All rights reserved.
//

#import "StartPSWViewController.h"
#import "ViewController.h"

@interface StartPSWViewController ()<UITextFieldDelegate>{
    UITextField *textFieldOne;
    UITextField *textFieldTwo;
    UITextField *textFieldThree;
    UITextField *textFieldFour;
    UILabel *lblMain;
    NSString *fristPSW;
}

@end

@implementation StartPSWViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setLeftBarItemsTitle:@[NSLocalizedString(@"Cancel_Sample", @"取消")]];
    if(_isVerify){
        [self setLeftBarItemsTitle:nil];
    }
    [self uiInit];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyBoard:)];
    [self.view addGestureRecognizer:tap];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldsNext:) name:UITextFieldTextDidChangeNotification object:nil];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillDisappear:(BOOL)animated{
    NSLog(@"PassWord：%@%@%@%@",textFieldOne.text,textFieldTwo.text,textFieldThree.text,textFieldFour.text);
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
-(void)uiInit{
    lblMain = [[UILabel alloc] initWithFrame:CGRectMake(0, 64+40*WIDTHSCALE, MAINSCREENBOUNDS.size.width, MAINSCREENBOUNDS.size.height/5.0)];
    lblMain.text = NSLocalizedString(@"PleaseEnterPSW_Sample",@"请输入密码");
    lblMain.textAlignment = NSTextAlignmentCenter;
    lblMain.textColor = COLOR_MAINHEAD;
    lblMain.font = TABLEHEADFONT;
    
    textFieldOne = [[UITextField alloc] initWithFrame:CGRectMake(20*WIDTHSCALE, lblMain.frame.origin.y+lblMain.frame.size.height, (MAINSCREENBOUNDS.size.width-100*WIDTHSCALE)/4.0, TEXTHEIGHT)];
    textFieldOne.backgroundColor = TEXTFIELDCOLOR;
    textFieldOne.layer.cornerRadius = 5.0;
    textFieldOne.layer.masksToBounds = YES;
    textFieldOne.textAlignment = NSTextAlignmentCenter;
    textFieldOne.delegate = self;
    [textFieldOne setSecureTextEntry:YES];
    textFieldOne.keyboardType = UIKeyboardTypePhonePad;
    [textFieldOne setValue:TEXTFONT forKeyPath:@"_placeholderLabel.font"];
    [textFieldOne becomeFirstResponder];
    
    textFieldTwo = [[UITextField alloc] initWithFrame:CGRectMake(textFieldOne.frame.origin.x+textFieldOne.frame.size.width+20*WIDTHSCALE, textFieldOne.frame.origin.y, textFieldOne.frame.size.width, textFieldOne.frame.size.height)];
    textFieldTwo.textAlignment = NSTextAlignmentCenter;
    textFieldTwo.backgroundColor = TEXTFIELDCOLOR;
    textFieldTwo.layer.cornerRadius = 5.0;
    textFieldTwo.layer.masksToBounds = YES;
    textFieldTwo.delegate = self;
    [textFieldTwo setSecureTextEntry:YES];
    textFieldTwo.keyboardType = UIKeyboardTypePhonePad;
    [textFieldTwo setValue:TEXTFONT forKeyPath:@"_placeholderLabel.font"];
    
    textFieldThree = [[UITextField alloc] initWithFrame:CGRectMake(textFieldTwo.frame.origin.x+textFieldTwo.frame.size.width+20*WIDTHSCALE, textFieldTwo.frame.origin.y, textFieldTwo.frame.size.width, textFieldTwo.frame.size.height)];
    textFieldThree.textAlignment = NSTextAlignmentCenter;
    textFieldThree.backgroundColor = TEXTFIELDCOLOR;
    textFieldThree.layer.cornerRadius = 5.0;
    textFieldThree.layer.masksToBounds = YES;
    textFieldThree.delegate = self;
    [textFieldThree setSecureTextEntry:YES];
    textFieldThree.keyboardType = UIKeyboardTypePhonePad;
    [textFieldThree setValue:TEXTFONT forKeyPath:@"_placeholderLabel.font"];

    textFieldFour = [[UITextField alloc] initWithFrame:CGRectMake(textFieldThree.frame.origin.x+textFieldThree.frame.size.width+20*WIDTHSCALE, textFieldThree.frame.origin.y, textFieldThree.frame.size.width, textFieldThree.frame.size.height)];
    textFieldFour.textAlignment = NSTextAlignmentCenter;
    textFieldFour.backgroundColor = TEXTFIELDCOLOR;
    textFieldFour.layer.cornerRadius = 5.0;
    textFieldFour.layer.masksToBounds = YES;
    textFieldFour.delegate = self;
    [textFieldFour setSecureTextEntry:YES];
    textFieldFour.keyboardType = UIKeyboardTypePhonePad;
    [textFieldFour setValue:TEXTFONT forKeyPath:@"_placeholderLabel.font"];
    
    [self.view addSubview:lblMain];
    [self.view addSubview:textFieldOne];
    [self.view addSubview:textFieldTwo];
    [self.view addSubview:textFieldThree];
    [self.view addSubview:textFieldFour];
    
}
-(void)hideKeyBoard:(UIGestureRecognizer *)gesture{
    [self.view endEditing:YES];
}




- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    NSLog(@"%s",__FUNCTION__);
    return YES;
}// return NO to disallow editing.
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    NSLog(@"%s",__FUNCTION__);
}// became first responder
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    NSLog(@"%s",__FUNCTION__);
    return YES;
}// return YES to allow editing to stop and to resign first responder status. NO to disallow the editing session to end
- (void)textFieldDidEndEditing:(UITextField *)textField{
    NSLog(@"%s",__FUNCTION__);
    if(textField.text.length>1){
        textField.text = [textField.text substringToIndex:1];
    }
}// may be called if forced even if shouldEndEditing returns NO (e.g. view removed from window) or endEditing:YES called

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    NSLog(@"%s",__FUNCTION__);
    if (string.length>1) {
        
    }
    return YES;
}// return NO to not change text

- (BOOL)textFieldShouldClear:(UITextField *)textField{
    NSLog(@"%s",__FUNCTION__);
    return YES;
}// called when clear button pressed. return NO to ignore (no notifications)
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    NSLog(@"%s",__FUNCTION__);
    return YES;
}


-(void)textFieldsNext:(NSNotification *)notification{
     NSLog(@"%s",__FUNCTION__);
    if (textFieldOne.isFirstResponder && textFieldOne.text.length==1) {
        [textFieldTwo becomeFirstResponder];
    }else if (textFieldTwo.isFirstResponder  && textFieldTwo.text.length==1){
        [textFieldThree becomeFirstResponder];
    }else if (textFieldThree.isFirstResponder && textFieldThree.text.length==1){
        [textFieldFour becomeFirstResponder];
    }else if(textFieldFour.isFirstResponder && textFieldFour.text.length==1){
        [textFieldFour resignFirstResponder];
        if (_isVerify) {
            UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width-15*WIDTHSCALE-80*WIDTHSCALE, 20+5*WIDTHSCALE, 80*WIDTHSCALE, 34*WIDTHSCALE)];
            button.layer.cornerRadius = button.frame.size.height/4.0;
            [button setBackgroundColor:TEXTFIELDCOLOR];
            [button addTarget:self action:@selector(rightAction:) forControlEvents:UIControlEventTouchUpInside];
            button.contentEdgeInsets = UIEdgeInsetsMake(5, 0, 5, 0);
            [button setTitle:NSLocalizedString(@"Complete_Sample", @"完成") forState:UIControlStateNormal];
            [self.view addSubview:button];
        }else{
            [self setRightBarItemsTitle:@[NSLocalizedString(@"Complete_Sample", @"完成")]];
        }
    }
}

-(void)rightAction:(id)sender{
    if (_isVerify) {
        NSString *psw = [[DBOperation getDBOperateInstance] selectPassWord];
        if ([psw isEqualToString:[NSString stringWithFormat:@"%@%@%@%@",textFieldOne.text,textFieldTwo.text,textFieldThree.text,textFieldFour.text]]) {
            ViewController *viewController = [[ViewController alloc] init];
            UIViewController *rootViewController = [[UINavigationController alloc]initWithRootViewController:viewController];
            [[UIApplication sharedApplication] keyWindow].rootViewController = rootViewController;
        }else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:NSLocalizedString(@"WrongPSW", @"错误密码") delegate:self cancelButtonTitle:NSLocalizedString(@"Sure_Sample",  @"确认") otherButtonTitles:nil];
            [alert show];
            textFieldOne.text = nil;
            [textFieldOne becomeFirstResponder];
            textFieldTwo.text = nil;
            textFieldThree.text = nil;
            textFieldFour.text = nil;
            [self setRightBarItemsTitle:nil];
        }
    }else{
        if (_startPSW) {
            if (!_secondStep) {
                fristPSW = [NSString stringWithFormat:@"%@%@%@%@",textFieldOne.text,textFieldTwo.text,textFieldThree.text,textFieldFour.text];
                textFieldOne.text = nil;
                [textFieldOne becomeFirstResponder];
                textFieldTwo.text = nil;
                textFieldThree.text = nil;
                textFieldFour.text = nil;
                [self setRightBarItemsTitle:nil];
                _secondStep = YES;
                lblMain.text = NSLocalizedString(@"PleaseEnterPSWAgain_Sample", nil);
                
                
            }else{
                if ([fristPSW isEqualToString:[NSString stringWithFormat:@"%@%@%@%@",textFieldOne.text,textFieldTwo.text,textFieldThree.text,textFieldFour.text]]) {
                    [[DBOperation getDBOperateInstance] insertPassWordWithString:fristPSW];
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:NSLocalizedString(@"StartPSWSuccess",@"启动密码成功") preferredStyle:UIAlertControllerStyleAlert];
                    [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Sure_Sample",  @"确定") style:UIAlertActionStyleDefault handler:^(UIAlertAction *alertAction){
                        NSLog(@"点击确认");
                        [self.navigationController popViewControllerAnimated:YES];
                    }]];
                    [self presentViewController:alert animated:YES completion:^{
                        
                    }];
                }else{
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:NSLocalizedString(@"PswSetWrong",@"两次密码输入不一致") delegate:self cancelButtonTitle:NSLocalizedString(@"Sure_Sample",  @"确定") otherButtonTitles:nil];
                    [alert show];
                    textFieldOne.text = nil;
                    [textFieldOne becomeFirstResponder];
                    textFieldTwo.text = nil;
                    textFieldThree.text = nil;
                    textFieldFour.text = nil;
                    [self setRightBarItemsTitle:nil];

                }
                
            }
        }else{
            NSString *psw = [[DBOperation getDBOperateInstance] selectPassWord];
            if ([psw isEqualToString:[NSString stringWithFormat:@"%@%@%@%@",textFieldOne.text,textFieldTwo.text,textFieldThree.text,textFieldFour.text]]) {
                [[DBOperation getDBOperateInstance] deletePassWord];
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:NSLocalizedString(@"ClosePSWSuccess",@"关闭密码成功") preferredStyle:UIAlertControllerStyleAlert];
                [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Sure_Sample",  @"确定") style:UIAlertActionStyleDefault handler:^(UIAlertAction *alertAction){
                    NSLog(@"点击确认");
                    [self.navigationController popViewControllerAnimated:YES];
                }]];
                [self presentViewController:alert animated:YES completion:^{
                    
                }];
            }else{
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:NSLocalizedString(@"WrongPsw", @"错误密码") delegate:self cancelButtonTitle:NSLocalizedString(@"Sure_Sample",  @"确定") otherButtonTitles:nil];
                [alert show];
                textFieldOne.text = nil;
                [textFieldOne becomeFirstResponder];
                textFieldTwo.text = nil;
                textFieldThree.text = nil;
                textFieldFour.text = nil;
                [self setRightBarItemsTitle:nil];
            }
            
        }
    }
}
@end
